import { Button, Checkbox, Col, DatePicker, Form, Row, Space, Table, Tabs, TreeSelect, message } from 'antd';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { useEffect, useMemo, useState } from 'react';
import Detailed from './Detailed';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import {
  fieldFlowExport,
  getInvoiceCode,
  getLevelZeroJson,
  getLoadMapList,
  getPosIDs,
  getSelectDataMapList,
  getTenantID,
  getUserDepID,
  getUserDepName,
  getUserID,
  getUserName,
} from '@/utils';
import { DownloadOutlined, CheckOutlined, SaveOutlined, UploadOutlined } from '@ant-design/icons';
import DifferTable from './DifferTable';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { connect } from 'umi';
import { requestController } from '../common/Format';
import { ExportdetServices, differServices, saveDifference } from '../services';
import moment from 'moment';
const CheckboxGroup = Checkbox.Group;

const DetailTab = ({ curRes, Detaildata }) => {
  const styleFixCls = 'contract-styfixcls-';

  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  /** 资产类型 */
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  const getdifferCallback = (res) => {
    if (acceptForm && res?.msgFlag) {
      acceptForm.setFieldsValue(
        // res.obj
        {
          ...res.obj,
          rangeStartDate: moment(res?.obj?.rangeStartDate, 'YYYY-MM-DD'),
          rangeEndDate: moment(res?.obj?.rangeEndDate, 'YYYY-MM-DD'),
        },
      );
    }
  };

  const getSaveDifRunCallback = (res) => {
    if (res?.msgFlag) {
      message.success('暂存成功');
      arrayList = [];
    }
  };

  const [titleValue, setTitleValue] = useState(null);

  /** 导出回调 */
  const exportCallback = (res: any) => {
    fieldFlowExport(res, `${titleValue}.xlsx`);
  };

  // 导出接口
  const { ExportRun } = ExportdetServices(exportCallback, curRes);

  const { DifferRun, Differdata } = differServices(curRes, getdifferCallback);
  const { SaveDifRun } = saveDifference(curRes, getSaveDifRunCallback);

  const [acceptForm] = Form.useForm();
  const [rangeType, setRangeType] = useState([]);
  const [rangeDeptID, setRangeDeptID] = useState<any>('');
  const [rangeAssetTypeID, setRangeAssetTypeID] = useState('');
  const [activeKey, setActiveKey] = useState('001');
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  let arrayList: any = [];
  // 工作流
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  /** 处理工作流功能 权限 */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (Differdata?.state == `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`;
    const taskHandInfo: Record<string, any> = Differdata?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [Differdata]);

  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  const saveList = (data) => {
    if (arrayList?.length > 0) {
      let flag = true;
      for (let index = 0; index < arrayList?.length; index++) {
        let element: any = arrayList[index];
        if (element?.id == data?.id) {
          flag = false;
        }
      }
      if (flag) {
        arrayList.push(data);
      }
    } else {
      arrayList.push(data);
    }
  };

  useEffect(() => {
    if (Detaildata?.obj?.id) {
      const obj: any = {
        inventoryID: Detaildata?.obj?.id,
      };
      DifferRun(obj);
    }
  }, [Detaildata]);

  const fromArray: any = [
    {
      key: 'accept-basic',
      title: '',
      fieldChildren: [
        {
          field: `inventoryerName`,
          label: `盘点人`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `inventoryDepartmentName`,
          label: `部门范围`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `userName`,
          label: `发起人`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `useDepartmentName`,
          label: `发起部门`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `createrName`,
          label: `盘点计划标题`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `inventoryTime`,
          label: `盘点时间`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `billNum`,
          label: `账面总数`,
          // initialValue: getUserName(),
          component: 'Input',
          disabled: true,
          placeholder: '请输入',
        },
        {
          field: `billSum`,
          label: `账面总额`,
          component: 'Input',
          // initialValue: getUserDepName(),
          placeholder: '请输入',
        },
        {
          field: `inventoryNum`,
          label: `盘点总数`,
          component: 'Input',
          placeholder: '请输入',
        },
        {
          field: `inventorySum`,
          label: `盘点总额`,
          // initialValue: getInvoiceCode('PD'),
          disabled: true,
          component: 'Input',
          placeholder: '请输入',
        },

        {
          field: `lossSum`,
          label: `盘亏汇总`,
          component: 'Input',
          placeholder: '请输入',
          //   render: (text) => {
          //     return <DatePicker format={'YYYY-MM-DD'} disabledDate={disabledDate} showTime disabledTime={disabledTime} />;
          //   },
        },
        {
          field: `surplusSum`,
          label: `盘盈汇总`,
          component: 'Input',
          placeholder: '请输入',
          //   render: (text) => {
          //     return <DatePicker format={'YYYY-MM-DD'} disabledDate={disabledDate} showTime disabledTime={disabledTime} />;
          //   },
        },
        {
          field: `inventoryInfo`,
          label: `盘点说明`,
          component: 'InputTextArea',
          // disabled: disabled,
          placeholder: '请输入',
          // required: !disabled,
          colSpan: 2,
          allowClear: true,
          showCount: true,
          maxLength: 200,
          autoSize: { minRows: 2, maxRows: 4 },
        },
        {
          field: `rangeType`,
          label: `盘点范围`,
          component: 'Render',
          // disabled: locationProps.state === 'view',
          placeholder: '请输入',
          colSpan: 2,
          render: () => {
            return (
              <CheckboxGroup
                options={[
                  {
                    value: '1',
                    label: '部门范围',
                  },
                  {
                    value: '2',
                    label: '资产类型范围',
                  },
                  {
                    value: '3',
                    label: '时间范围',
                  },
                ]}
                value={rangeType}
                onChange={(list: any) => {
                  setRangeType(list);
                }}
              />
            );
          },
        },
        {
          field: `rangeDeptID`,
          label: `部门范围`,
          component: 'Render',
          colSpan:
            rangeType.length == 1 && rangeType[0] == '1'
              ? 2
              : rangeType.length > 0 && (rangeType[0] == '1' || rangeType[1] == '1' || rangeType[2] == '1')
              ? 1
              : 0,
          // disabled: locationProps.state === 'view',
          placeholder: '请输入',
          render: (text) => {
            return (
              <TreeSelect
                multiple
                style={{
                  width: '100%',
                }}
                dropdownStyle={{
                  maxHeight: 400,
                  overflow: 'auto',
                }}
                fieldNames={{
                  label: 'text',
                  value: 'id',
                  children: 'children',
                }}
                onChange={(value) => {
                  setRangeDeptID(value);
                }}
                treeData={getLevelZeroJson()}
                treeCheckable={true}
              />
            );
          },
        },
        {
          field: `rangeAssetTypeID`,
          label: `资产类型`,
          component: 'Render',
          colSpan:
            rangeType.length == 1 && rangeType[0] == '2'
              ? 2
              : rangeType.length > 0 && (rangeType[0] == '2' || rangeType[1] == '2' || rangeType[2] == '2')
              ? 1
              : 0,
          // disabled: locationProps.state === 'view',
          placeholder: '请输入',
          render: (text) => {
            return (
              <TreeSelect
                multiple
                style={{
                  width: '100%',
                }}
                onChange={(value) => {
                  setRangeAssetTypeID(value);
                }}
                dropdownStyle={{
                  maxHeight: 400,
                  overflow: 'auto',
                }}
                fieldNames={{
                  label: 'name',
                  value: 'id',
                  children: 'children',
                }}
                treeData={assetType}
                treeCheckable={true}
              />
            );
          },
        },
        {
          field: `rangeStartDate`,
          label: `取得开始时间`,
          component: 'Render',
          colSpan:
            rangeType.length == 1 && rangeType[0] == '3'
              ? 1
              : rangeType.length > 0 && (rangeType[0] == '3' || rangeType[1] == '3' || rangeType[2] == '3')
              ? 1
              : 0,
          // disabled: locationProps.state === 'view',
          placeholder: '请输入',
          render: (text) => {
            return <DatePicker format={'YYYY-MM-DD'} />;
          },
        },
        {
          field: `rangeEndDate`,
          label: `取得结束时间`,
          component: 'Render',
          colSpan:
            rangeType.length == 1 && rangeType[0] == '3'
              ? 1
              : rangeType.length > 0 && (rangeType[0] == '3' || rangeType[1] == '3' || rangeType[2] == '3')
              ? 1
              : 0,
          // disabled: locationProps.state === 'view',
          placeholder: '请输入',
          render: (text) => {
            return <DatePicker format={'YYYY-MM-DD'} />;
          },
        },
      ],
    },
    {
      key: 'accept-procurement',
      title: '',
      fieldCustomDom: (
        <>
          <DifferTable datalist={{ ...Detaildata?.obj }} saveList={saveList} />
        </>
      ),
    },
  ];

  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: acceptForm,
    schemas: fromArray,
  });

  /** 返回tab子页面 */
  const tabsItem = useMemo(() => {
    let items: any[] = [
      {
        label: '盘点明细',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 0px' }}>
                <Detailed datalist={{ ...Detaildata?.obj }} />
              </ScrollBarLayout>
            </div>

            <div
              className="tabsBodyBottomBtn"
              style={{
                textAlign: 'center',
              }}
            >
              <Space>
                {Differdata?.obj.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1000` ||
                Differdata?.obj.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1002` ||
                Differdata?.obj.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1004` ? (
                  <>
                    <UploadFormCommon
                      form={acceptForm}
                      fileFormName={'reportURL'}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      accept={'.zip'}
                      url={'/assetInventoryDifference/importPicture'}
                      downloadUrl={''} // 下载
                      fileFormDelName={'delFile'}
                      uploadSuccessCallback={(attachPaths) => {
                        acceptForm?.setFieldsValue({
                          reportURL: attachPaths,
                        });
                      }}
                      defaultFiles={''}
                      maxFile={1}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'reportURL'}
                      delFunc={(delFilePath) => {
                        // acceptForm?.setFieldsValue({
                        //   assetImage: '',
                        // });
                      }}
                    >
                      上传结果
                    </UploadFormCommon>
                    <UploadFormCommon
                      form={acceptForm}
                      fileFormName={'reportURL'}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      accept={'.zip'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      uploadSuccessCallback={(attachPaths) => {
                        acceptForm?.setFieldsValue({
                          reportURL: attachPaths,
                        });
                      }}
                      defaultFiles={''}
                      maxFile={1}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'reportURL'}
                      delFunc={(delFilePath) => {
                        // acceptForm?.setFieldsValue({
                        //   assetImage: '',
                        // });
                      }}
                    >
                      上传图片集
                    </UploadFormCommon>
                  </>
                ) : null}

                <Button
                  icon={<DownloadOutlined />}
                  style={{ marginBottom: 24 }}
                  type={'primary'}
                  onClick={() => {
                    setTitleValue(Detaildata.obj.inventoryTitle);
                    const obj: any = {
                      inventoryID: Detaildata.obj.id,
                    };
                    ExportRun(obj);
                  }}
                >
                  导出
                </Button>
              </Space>
            </div>
          </div>
        ),
      },
      {
        label: '差异明细',
        key: '002',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>

            <div
              className="tabsBodyBottomBtn"
              style={{
                textAlign: 'center',
              }}
            >
              <Space>
                {Differdata?.obj.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1000` ||
                Differdata?.obj.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1002` ||
                Differdata?.obj.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_SUMMARY_STATUS}1004` ? (
                  <>
                    <Button
                      style={{ marginBottom: 24 }}
                      icon={<SaveOutlined />}
                      type={'primary'}
                      onClick={() => {
                        if (arrayList) {
                          SaveDifRun(arrayList);
                        }
                      }}
                    >
                      保存
                    </Button>
                    <Button
                      style={{ marginBottom: 24 }}
                      icon={<CheckOutlined />}
                      type={'primary'}
                      onClick={() => {
                        const obj = {
                          ...Differdata?.obj,
                          createDepartmentID: getUserDepID(),
                          createPositionID: getPosIDs(),
                          createrID: getUserID(),
                          inventoryID: Detaildata?.obj?.id,
                          businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`,
                        };
                        setWorkFlowInfoObj({
                          selectFlowRows: obj,
                          showWorkFlowModal: true,
                          saveNoDefaultFlowID: '',
                        });
                      }}
                    >
                      提交
                    </Button>
                  </>
                ) : null}
              </Space>
            </div>
          </div>
        ),
      },
    ];
    return items;
  }, [rangeType, Differdata]);

  return (
    <div className={Cls('list-table', `${styleFixCls}updateStepsBox-tableBox`)}>
      <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
        <Col span={24} className={`${styleFixCls}row-col`}>
          <Tabs
            className={pageStyles['commonTabs']}
            type="card"
            onChange={(activeKey: string) => {
              setActiveKey(activeKey);
            }}
            items={tabsItem}
            destroyInactiveTabPane={true}
          />
        </Col>
      </Row>

      {/* 工作流-----审批记录 */}
      {Differdata?.obj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`] && activeKey == '002' && (
        <WorkflowChedkRecord
          curRes={curRes}
          dataDetailInfo={Differdata?.obj}
          flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`}
          requestController={requestController()}
          reloadPageCallback={() => {
            // getDetailRun({ id: detailInfo?.id });
          }} // 刷新方法-详情方法
          revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1000`}
          allBtnFuncQuqry={workflowPowerAllBtn}
          tabPaneHeight={0.35}
          isCheckDrawer={true}
          isShowCollapse={isShowWorkRecord}
          changeCollapse={(val) => {
            setIsShowWorkRecord(val);
          }}
          cancelStateId={`${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1003`}
          isSyncArchive={true}
        />
      )}

      {/* 工作流-----发起流程审批弹窗 */}
      {workFlowInfoObj?.showWorkFlowModal && (
        <WorkflowSwitchModal
          openVisible={workFlowInfoObj?.showWorkFlowModal}
          businessInfoObj={workFlowInfoObj?.selectFlowRows}
          requestController={'assetInventoryDifference'}
          orderType={`${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_ORDER}1030`}
          category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`}
          businessCategory={``}
          selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          reloadInfoCallback={() => {
            // getDetailReload();
          }}
          openFlowChangeModal={setShowSwitchFlow}
          onClose={() => {
            setWorkFlowInfoObj({
              ...workFlowInfoObj,
              showWorkFlowModal: false,
            });
          }}
          replaceStrObj={{ own: 'own', workflowType: 'category' }}
        />
      )}
      {/* 挑选流程组件 */}
      {showSwitchFlow && (
        <WorkflowNoDefaultTable
          openVisibleSwitch={showSwitchFlow}
          onCloseSwitch={closeSwitchFlowModal}
          requestController={'assetInventoryDifference'}
          orderType={workFlowInfoObj?.selectFlowRows?.orderType || `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1030`}
          category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1019`}
          businessCategory={`${getTenantID()}${ILoadMapTypeAll.ASSET_INNENTORY_STATUS}1000`}
          saveSelectFlowID={(flowId: string) => {
            setWorkFlowInfoObj({
              ...workFlowInfoObj,
              saveNoDefaultFlowID: flowId,
            });
          }}
          selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
        />
      )}
    </div>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(DetailTab);
